package com.top.servlet;


import com.top.service.userService;
import com.top.service.userServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user_name = req.getParameter("user_name");//获取输入的用户名和密码
        String password = req.getParameter("password");
        String verifyCode = req.getParameter("verifyCode");//获取输入的验证码
        userService userService = new userServiceImpl();
        boolean flag = userService.login(user_name, password);//在数据库判断密码是否正确
        String verify = (String) req.getSession().getAttribute("code");//在session获取验证码的值
        //判断验证码是否一致
        if (verifyCode.equals(verify)){
            if (flag) {
                req.getSession().setAttribute("login",true);
                req.getSession().removeAttribute("msg");
                req.getRequestDispatcher("index.jsp").forward(req,resp);
            }else {
                req.getSession().setAttribute("login",false);
                req.getSession().setAttribute("msg","用户名或密码错误");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }
        }else {
            req.getSession().setAttribute("msg","验证码错误");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }

    }
}
